package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.wms.entity.WmsWarehouse;
import org.jeecg.modules.wms.entity.WmsWarehouseLocation;
import org.jeecg.modules.wms.mapper.WmsWarehouseMapper;
import org.jeecg.modules.wms.service.IWmsWarehouseLocationService;
import org.jeecg.modules.wms.service.IWmsWarehouseService;
import org.jeecg.modules.wms.vo.WmsWarehouseLocationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 仓库信息服务实现类
 */
@Service
public class WmsWarehouseServiceImpl extends ServiceImpl<WmsWarehouseMapper, WmsWarehouse> implements IWmsWarehouseService {

    @Autowired
    private IWmsWarehouseLocationService wmsWarehouseLocationService;
    
    @Override
    public IPage<WmsWarehouseLocationVO> queryWarehousePageList(Page<WmsWarehouse> page, WmsWarehouse warehouse) {
        // 创建新的Page对象，保持与原方法一致
        Page<WmsWarehouseLocationVO> voPage = new Page<>(page.getCurrent(), page.getSize());
        
        // 调用原有方法
        return baseMapper.queryWarehousePageList(voPage, warehouse);
    }

    @Override
    public WmsWarehouseLocationVO queryWarehouseById(String id) {
        return baseMapper.queryWarehouseById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWarehouse(WmsWarehouse wmsWarehouse) {
        // 设置租户ID
        String tenantId = TenantContext.getTenant();
        if (StringUtils.isNotBlank(tenantId)) {
            wmsWarehouse.setTenantId(tenantId);
        }
        
        // 检查仓库编号是否已存在（在当前租户下唯一）
        if (StringUtils.isBlank(wmsWarehouse.getWarehouseCode())) {
            throw new JeecgBootException("仓库编号不能为空");
        }
        
        LambdaQueryWrapper<WmsWarehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmsWarehouse::getWarehouseCode, wmsWarehouse.getWarehouseCode());
        if (StringUtils.isNotBlank(tenantId)) {
            queryWrapper.eq(WmsWarehouse::getTenantId, tenantId);
        }

        Long count = count(queryWrapper);
        if (count > 0) {
            throw new JeecgBootException("仓库编号已存在，请更换其他编号");
        }
        
        return save(wmsWarehouse);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWarehouse(WmsWarehouse wmsWarehouse) {
        // 检查仓库编号是否已存在（在当前租户下唯一，排除自身）
        if (StringUtils.isBlank(wmsWarehouse.getWarehouseCode())) {
            throw new JeecgBootException("仓库编号不能为空");
        }
        
        String tenantId = TenantContext.getTenant();
        
        LambdaQueryWrapper<WmsWarehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmsWarehouse::getWarehouseCode, wmsWarehouse.getWarehouseCode())
                  .ne(WmsWarehouse::getId, wmsWarehouse.getId());
        if (StringUtils.isNotBlank(tenantId)) {
            queryWrapper.eq(WmsWarehouse::getTenantId, tenantId);
        }
        
        Long count = count(queryWrapper);
        if (count > 0) {
            throw new JeecgBootException("仓库编号已存在，请更换其他编号");
        }
        
        return updateById(wmsWarehouse);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteWarehouse(String id) {
        // 查询库位
        List<WmsWarehouseLocation> locationList = wmsWarehouseLocationService.queryLocationListByWarehouseId(id);
        if (locationList != null && !locationList.isEmpty()) {
            throw new JeecgBootException("该仓库下存在库位，无法删除！");
        }
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteWarehouse(String ids) {
        if (StringUtils.isBlank(ids)) {
            return false;
        }
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            deleteWarehouse(id);
        }
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleWarehouseStatus(String id) {
        WmsWarehouse warehouse = getById(id);
        if (warehouse == null) {
            throw new JeecgBootException("仓库不存在");
        }
        
        // 切换状态 1-启用，0-禁用
        String status = "1".equals(warehouse.getStatus()) ? "0" : "1";
        warehouse.setStatus(status);
        
        return updateById(warehouse);
    }
    
    @Override
    public WmsWarehouse getRecommendedWarehouse(String materialTypes) {
        if (StringUtils.isBlank(materialTypes)) {
            return null;
        }
        
        // 解析物料类型
        String[] typeArray = materialTypes.split(",");
        
        // 查询所有启用状态的仓库
        LambdaQueryWrapper<WmsWarehouse> warehouseQuery = new LambdaQueryWrapper<>();
        warehouseQuery.eq(WmsWarehouse::getStatus, "0"); // 0-启用
        List<WmsWarehouse> warehouses = this.list(warehouseQuery);
        
        if (warehouses == null || warehouses.isEmpty()) {
            return null;
        }
        
        // 对于每个仓库，检查是否支持所有物料类型
        for (WmsWarehouse warehouse : warehouses) {
            // 获取仓库类型
            String warehouseType = warehouse.getWarehouseType();
            
            // 检查仓库类型是否支持所有物料类型
            boolean isRecommended = true;
            for (String materialType : typeArray) {
                // 根据业务规则判断仓库类型是否支持该物料类型
                if (!isSupportedMaterialType(warehouseType, materialType)) {
                    isRecommended = false;
                    break;
                }
            }
            
            // 如果该仓库适合所有物料类型，则推荐
            if (isRecommended) {
                return warehouse;
            }
        }
        
        // 如果没有找到完全匹配的仓库，返回第一个仓库
        return warehouses.get(0);
    }
    
    /**
     * 判断仓库类型是否支持指定的物料类型
     * @param warehouseType 仓库类型
     * @param materialType 物料类型
     * @return 是否支持
     */
    private boolean isSupportedMaterialType(String warehouseType, String materialType) {
        // 如果仓库类型为空，不支持任何物料类型
        if (StringUtils.isBlank(warehouseType)) {
            return false;
        }
        
        // 严格按照仓库类型和物料类型一一对应
        switch (warehouseType) {
            case "1": // 型材库(1)只能存放型材(1)
                return "1".equals(materialType);
            case "2": // 配件库(2)只能存放配件(2)
                return "2".equals(materialType);
            case "3": // 辅件库(3)只能存放辅件(3)
                return "3".equals(materialType);
            case "4": // 其他库(4)只能存放其他物料(4)
                return "4".equals(materialType);
            case "5": // 余料库(5)只能存放余料(5)
                return "5".equals(materialType);
            case "6": // 半料库(6)只能存放半料(6)
                return "6".equals(materialType);
            case "7": // 成品库(7)暂不使用
            case "8": // 半成品库(8)暂不使用
            case "0": // 通用仓库暂不使用
                return false;
            default:
                return false;
        }
    }
} 